import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Form, Input, Modal, Checkbox, Button, Upload, Row, Col } from 'antd';
import PateoTable from '@/components/common/PateoTable';
// import FileModal from './fileModal'
import { SmileOutlined, FrownOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import { getToken } from '@/utils/utils';
import { getMd5 } from '@/utils/utils';
import FileView from '@/components/FileView';

const mapStateToProps = (state: any) => ({
  breakdownSearch: state.breakdownSearch,
  loading: state.loading.effects['http/getFetchPage'],
});

class CaseViewModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    let userAccount: any = '';
    try {
      userAccount = sessionStorage.getItem('accountName');
    } catch (e) {}
    this.state = {
      userAccount: userAccount,
      fileVisible: false,
      viewFileInfo: {},
      viewHeight: 100,
      formValues: {},
      list: [], //  案例文档列表
      pagination: {},
      fileViewVisible: false,
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, record, dispatch } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      //  查询案例列表
      dispatch({
        type: 'http/getFetchPage',
        payload: { 
          url: '/mscontent/knowledge/fault/case/list',
          faultCode: record.faultCode,
          majorCode: record.majorCode,
        },
        callback: (res: any) => {
          if (res.statusCode === '0') {
            this.setState({
              list: res.data.list || [],
              pagination: res.data.pagination || {}
            })
          }
        }
      })
    }
  }

  //  关闭操作
  cancel = () => {
    const { closeModal } = this.props;
    closeModal();
  };

  //  查看文档
  handleView = (record: any) => {
    //  当前视口高
    const viewHeight = document.documentElement.scrollHeight - 100;
    this.setState({
      fileViewVisible: true,
      viewHeight: viewHeight > 100 ? viewHeight : 100
    }, () => {
      this.fileViewRef?.setData({
        ...record,
      })
    })
  }

  //  关闭文档预览弹框
  closeView = () => {
    this.setState({
      fileViewVisible: false
    })
  }

  //  关闭弹框
  closeFileModal = (record: any) => {
    this.setState({
      fileVisible: false,
      viewFileInfo: {}
    })
  }

  //  反馈
  handleFeedback = (type: number) => {
    const { dispatch, record: { faultCode, majorCode } } = this.props;
    const { userAccount } = this.state;
    dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/findSidByAccountName',
        accountName: userAccount || '',
      },
      callback: (res: any) => {
        if (res.statusCode) {
          dispatch({
            type: 'http/postObjWithRes',
            payload: {
              url: '/mscontent/knowledge/fault/userfeedback/save',
              majorCode,
              faultCode,
              userId: res.data || '',
              userFeedback: type,
            },
            callback: (res: any) => {
              if (res.statusCode) {
                message.success('已反馈成功');
              }
            }
          })
        }
      }
    })
  }

  render() {
    const { modalVisible, dispatch, record, pathname, loading } = this.props;
    const { formValues, fileVisible, viewFileInfo, viewHeight, list, pagination, fileViewVisible } = this.state;
    const title = `(${record.faultCode || ''})${record.faultType || ''}`;
    const page = {
      current: pagination?.current || 1,
      pageSize: pagination?.pageSize || 1,
      total: pagination.total || 0,
    }
    const columns = [
      {
        title: '文件名称',
        dataIndex: 'fileName',
        render: (text: any, record: any) => {
          return <Button type="link" style={{ padding: 0 }} onClick={() => this.handleView(record)}>{text}</Button>;
        }

      },
    ]
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{page === undefined ? 0 : page.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
      onChange: (pagination: any, filters: any, sorter: any, extra: any) => {
        const { current, pageSize } = pagination;
        //  查询案例列表
        dispatch({
          type: 'http/getFetchPage',
          payload: { 
            url: '/mscontent/knowledge/fault/case/list',
            id: record.id,
            current,
            pageSize,
          },
          callback: (res: any) => {
            if (res.statusCode === '0') {
              this.setState({
                list: res.data.list || [],
                pagination: res.data.pagination || {}
              })
            }
          }
        })
      }
    };
    
    const footer = (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <div>
          <span>以上内容是否对你有帮助：</span>
          <Button onClick={() => { this.handleFeedback(1) }} style={{ fontSize: '16px', color: '#90C63C' }} type="link" icon={<SmileOutlined />}><span style={{ fontSize: '13px' }}>有帮助</span></Button>
          <Button onClick={() => { this.handleFeedback(0) }} style={{ fontSize: '16px', color: '#DC152E' }} type="link" icon={<FrownOutlined />}><span style={{ fontSize: '13px' }}>没帮助</span></Button>
        </div>
        <Button size="small" onClick={this.cancel}>
          关闭
        </Button>
      </div>
    );

    return (
      <Modal
        style={{ top: 20 }}
        footer={footer}
        width={700}
        title={title}
        visible={modalVisible}
        onCancel={this.cancel}
      >
        <PateoTable
          extraHandle={true}
          tableProps={tableProps}
          fetchParams={{ type: 'http/getFetchPage', url: '/mscontent/knowledge/fault/case/list',  }}
          formValues={formValues}
        />

        <Modal
          style={{ top: 20 }}
          footer={null}
          width={'100%'}
          title="案例文件"
          bodyStyle={{
            height: viewHeight,
            maxHeight: viewHeight
          }}
          visible={fileViewVisible}
          onCancel={this.closeView}
        >
          <FileView onRef={(modalRef: any) => (this.fileViewRef = modalRef)} />
        </Modal>
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(CaseViewModal);
